import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = () => {
  return new Vuex.Store({
    state: {
      works: [],
      drawer: false,
      isdark: false,
      items: [
        {
          text: '主页',
          href: '/',
        },
      ],
    },
    getters: {
      categories: state => {
        const categories = []
  
        for (const work of state.works) {
          if (
            !work.category ||
            categories.find(category => category.text === work.category)
          ) continue
  
          const text = work.category
          const str = '观点记录片人物猎奇'
          const i = str.indexOf(text)
          let link
          switch (i){
            case 0:link="viewpoint";
            break;
            case 2:link="documentary";
              break;
            case 5:link="personage";
              break;
            case 7:link="curiosity";
            break;
            case -1:link="other";
            break;
         }
  
          categories.push({
            text,
            href: link,
          })
        }
  
        return categories.sort().slice(0, 5)
      },
      links: (state, getters) => {
        return state.items.concat(getters.categories)
      },
    },
    mutations: {
      setDrawer: (state, payload) => (state.drawer = payload),
      toggleDrawer: state => (state.drawer = !state.drawer),
      setWorks(state,args) {
        state.works = args
      },
      setTheme(state,args){
        state.isdark = args
      }
    },
    actions: {
      setWorks({commit},args) {
        commit('setWorks',args)
      },
      nuxtServerInit ({ commit }, {req}) {
        const str = req.headers.cookie
        if(!str) return
        if (str.indexOf('isdark')!==-1) {
          const isdark = str.substr(str.indexOf('isdark')+7,4) === 'true' ? true: false
          commit('setTheme', isdark)
        }
      }
    },
  })
}

export default store
